from django.http import JsonResponse
from rest_framework.response import Response
# Create your views here.
from django.views import View
from rest_framework.utils import json
from rest_framework.views import APIView

from apps.recruits.models import Enterprise, Recruit, City
from apps.recruits.serializers import Enterpriseserializer, RecruitSerializer, CitySerializer, RecruitSerializerez, \
    Enterpriseserializerez
from apps.users.models import User

"""功能清单:  
获取推荐职位信息   获取最新职位信息   获取热门企业信息   获取热门城市信息  索职位信息  职位详情的展示  
收藏职位     取消收藏职位增加职位访问次数  企业详情展示  收藏企业  取消收藏企业  增加企业访问次数
"""

# 获取推荐的招聘信息列表  已改
class RecruitListGenericView(APIView):

    """ 1.获取推荐的招聘信息列表    GET   /recruits/search/recommend/  """

    def get(self, request):
        # recruit = Recruit.objects.filter(state=1)[0:5]
        queryset = Recruit.objects.all().order_by('-id')[:4]
        serializer = RecruitSerializer(queryset, many=True)
        # print(serializer.data)
        return Response(serializer.data)


# 获取最新的招聘信息列表 已改
class RecruitnewListGenericView(APIView):
    """  获取最新的招聘信息列表  GET  /recruits/search/latest/ """

    def get(self, request):
        recruits = Recruit.objects.filter().order_by('-createtime')[0:5]
        serializer = RecruitSerializer(recruits, many=True)
        return Response(serializer.data)

# 获取热门企业列表 已改
class EnterpriseListGenericView(APIView):
    """  获取热门企业列表  GET  /enterprise/search/hotlist/ """

    def get(self, request):
        enterprises = Enterprise.objects.filter().order_by('visits')
        serializer = Enterpriseserializer(enterprises, many=True)
        return Response(serializer.data)

# 获取热门城市 已改
class CityListView(APIView):
    """  获取热门城市  GET  /city/hotlist/   """

    def get(self, request):
        cities = City.objects.filter(ishot=1)
        serializer = CitySerializer(cities, many=True)
        return Response(serializer.data)

# 搜索某个职位
class SearchRecruitListView(APIView):
    """   搜索某个职位  Path： POST  /recruits/search/city/keyword/ """

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('cityname')
        keyword = json_dict.get('keyword')

        if name and keyword:
            recruits = Recruit.objects.filter(city=name, jobname__contains=keyword)
            serializer = RecruitSerializer(recruits, many=True)
            return Response(serializer.data)
        elif name:
            recruits = Recruit.objects.filter(city=name)
            serializer = RecruitSerializer(recruits, many=True)
            return Response(serializer.data)
        else:
            recruits = Recruit.objects.all().order_by('visits')
            serializer = RecruitSerializer(recruits, many=True)
            return Response(serializer.data)

# ok
# 获取职位详情信息 　
class GetRecruitListView(APIView):
    """  获取职位详情信息  Path： GET   /recruits/{id}/ """

    def get(self, request,pk):
        # Recruits = Recruit.objects.get(pk=pk)
        # serializer = RecruitSerializerez(instance=Recruits, many=True)
        # return Response(serializer.data)
        try:
            recruits = Recruit.objects.get(id=pk)
        except Recruit.DoesNotExist:
            raise Response({'message': 'not found'}, status=404)

            # 创建序列化器
        serializer = RecruitSerializer(recruits)
        # 返回数据
        return Response(serializer.data)


# 增加某个职位访问量 已改
class AddRecruitViewSet(APIView):
    """  增加某个职位访问量   Path： PUT  /recruits/{id}/visit/ """

    def put(self, request, pk):
        visits_recruit = Recruit.objects.get(pk=pk)
        visits_recruit.visits += 1
        visits_recruit.save()
        return Response({"message": "更新成功", "success": True})


# 8. 收藏或者取消收藏职位  已改
class CollectecruitAPIView(APIView):
    """ 收藏或者取消收藏职位  Path： POST /recruits/{id}/collect/ """

    def post(self, request, pk):
        recruit = Recruit.objects.get(id=pk)
        user = User.objects.get(username=request.user.username)
        recruit.users.add(user)
        recruit.save()
        return Response({"message": "收藏成功", "success": True})

class CancelcollectecruitAPIView(APIView):
    def post(self, request, pk):
        recruit = Recruit.objects.get(id=pk)
        user = User.objects.get(username=request.user.username)
        recruit.users.remove(user)
        recruit.save()
        return Response({"message": "收藏成功", "success": True})

class VisitAPIView(APIView):
    def put(self,requset,pk):
        visits_recruit = Recruit.objects.get(pk=pk)
        visits_recruit.visits += 1
        visits_recruit.save()
        return Response({"message": "更新成功", "success": True})



# 9. 获取企业详情信息
class EnterpriseAPIView(APIView):
    """  获取职位详情信息  Path： GET   /enterprise/{id}/ """

    def get(self, request, pk):
        # enterprise = Enterprise.objects.get(pk=pk)
        # serializer = Enterpriseserializer(instance=enterprise, many=True)
        # return Response(serializer.data)
        try:
            enterprise = Enterprise.objects.get(id=pk)
        except Enterprise.DoesNotExist:
            raise JsonResponse({'message': 'not found'}, status=404)
        serializer = Enterpriseserializerez(enterprise)
        return JsonResponse(serializer.data)


# 10 增加企业的访问量
class EnterprisevisitAPIView(APIView):
    """  增加企业的访问量   Path： PUT   /enterprise/{id}/visit/  """

    def put(self, request, pk):
        visits_enterprise = Enterprise.objects.get(pk=pk)
        visits_enterprise.visits += 1
        visits_enterprise.save()
        return Response({"message": "更新成功", "success": True})


# 11 . 收藏公司或者取消收藏公司,后台会自行动态判断
class CollectEnterpriseAPIView(APIView):
    """   收藏公司或者取消收藏公司,后台会自行动态判断
          Path： POST /enterprise/{id}/collect/
    """
    def post(self, request, pk):
        enterprise = Enterprise.objects.get(id=pk)
        user = User.objects.get(username=request.user.username)
        enterprise.users.add(user)
        enterprise.save()
        return Response({"message":"收藏成功", "success": True})

class CancelcollectEnterpriseAPIView(APIView):
    def post(self, request, pk):
        enterprise = Enterprise.objects.get(id=pk)
        user = User.objects.get(username=request.user.username)
        enterprise.users.remove(user)
        enterprise.save()
        return Response({"message": "收藏成功", "success": True})
